package com.css.gdzj.gdzjbxgd.modules.userinfo.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.gdzj.gdzjbxgd.common.util.R;
import com.css.gdzj.gdzjbxgd.modules.userinfo.repository.entity.UserInfoEntity;
import com.css.gdzj.gdzjbxgd.modules.userinfo.service.UserInfoService;
import com.css.gdzj.gdzjbxgd.modules.userinfo.viewobjects.UserInfoQueryParams;
import com.querydsl.core.QueryResults;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigInteger;
import java.util.*;

/**
 * @author z
 * @date 2020-12-11
 */
@Slf4j
@RestController
@RequestMapping("/userInfos")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;

    /**
     *
     * @param userName
     * @param userUnit
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/queryUserInfos")
    public R queryUserInfos(@RequestParam(required = false) String loginName,
                            @RequestParam(required = false) String userName,
                            @RequestParam(required = false) String userPost,
                            @RequestParam(required = false) String userRank,
                            @RequestParam(required = false) String userLeaderPost,
                            @RequestParam(required = false) String userUnit,
                            @RequestParam(required = false) String userLevel,
                            @RequestParam(required = false) Integer pageNo,
                            @RequestParam(required = false) Integer pageSize) {
        try{
            PageRequest pageRequest = PageRequest.of(pageNo-1,pageSize);
            Map<String,Object> map = new HashMap<>();
            map = userInfoService.queryUserInfos(loginName,userName,userPost,userRank,userLeaderPost,userUnit,userLevel,pageNo,pageSize);
            List<UserInfoEntity> listUserInfo = (List) map.get("listUserInfo");
            BigInteger total1 = (BigInteger) map.get("total");
            int total= 0;
            if (total1 != null){
                total = total1.intValue();
            }
            Integer totalPage = 1;
            if (pageSize > 0 && total > 0 ){
                if (pageSize >= total){
                    totalPage = 1;
                }else {
                    totalPage = total/pageSize;
                    if (total % pageSize != 0){
                        totalPage ++;
                    }
                }
            }
            return R.ok().put("data",listUserInfo).put("total",total).put("totalPage",totalPage);
        }catch (Exception e){
            String errorMessage = "查询失败!";
            log.error(errorMessage,e);
            return R.error();
        }

    }

    @GetMapping("{id}")
    public R getUserInfo(@PathVariable String id) {
        try{
            UserInfoEntity userInfo = userInfoService.getUserInfo(id);
            return R.ok().put("data",userInfo);
        }catch (Exception e){
            String errorMessage = "获取失败!";
            log.error(errorMessage,e);
            return R.error();
        }
    }

    /**
     * 修改密码
     * @param userId
     * @param newPassword
     * @return
     */

     @PostMapping("/editPassword")
    public R editPassword(@RequestBody Map<String, String> params){
         try{
             String newPassword = params.get("newPassword");
                 String newPasswordMd5 = DigestUtils.md5Hex(newPassword);
                 UserInfoEntity userInfo = userInfoService.editPassword(params.get("userId"),newPasswordMd5);
                 if (null != userInfo){
                     return R.ok().put("message","修改密码成功!");
                 }else {
                     return R.ok().put("message","用户不存在!");
                 }


        }catch (Exception e){
            String errorMessage = "修改密码失败!";
            log.error(errorMessage,e);
            return R.error();
        }
    }

    @PostMapping("/resetPassword")
    public R resetPassword(@RequestBody Map<String, String> params){
        try{
                String userId = params.get("userId");
                String newPasswordMd5 = DigestUtils.md5Hex("abc123");
                UserInfoEntity userInfo = userInfoService.editPassword(userId,newPasswordMd5);
                if (null != userInfo){
                    return R.ok().put("message","修改密码成功!");
                }else {
                    return R.ok().put("message","用户不存在!");
                }
        }catch (Exception e){
            String errorMessage = "修改密码失败!";
            log.error(errorMessage,e);
            return R.error();
        }
    }
    @GetMapping("/checkUserLoginName")
    public R checkUserLoginName(@RequestParam String userLoginName){
        try{
            UserInfoEntity userInfo = userInfoService.checkUserLoginName(userLoginName);
            if (null != userInfo){
                return R.ok().put("code","502").put("message","账号不可用!");
            }else {
                return R.ok().put("code","200").put("message","账号可用!");
            }
        }catch (Exception e){
            String errorMessage = "修改密码失败!";
            log.error(errorMessage,e);
            return R.error();
        }
    }
    @PostMapping("/addUserinfo")
    public R saveUserInfo(@RequestBody UserInfoEntity userInfo) {
        JSONObject json = new JSONObject();
        try{
            userInfoService.saveUserInfo(userInfo);
            return R.ok();
        }catch (Exception e){
            String errorMessage = "新增失败!";
            log.error(errorMessage,e);
            return R.error();
        }
    }
    /*自动递增账户后四位*/
    @PostMapping("/getLoginNameLast")
    public R getLoginNameLast(@RequestParam String userLoginName) {
        JSONObject json = new JSONObject();
        try{
           String loginNameLast = userInfoService.getLoginNameLast(userLoginName);
            return R.ok().put("loginNameLast",loginNameLast);
        }catch (Exception e){
            String errorMessage = "获取账户后四位失败!";
            log.error(errorMessage,e);
            return R.error();
        }
    }
    @PostMapping("/controlReport")
    public R controlReport(@RequestBody Map<String, String> params)  {
        try{
            UserInfoEntity userInfo = userInfoService.controlReport(params);
            if (null != userInfo){
                return R.ok().put("message","更改成功!");
            }else {
                return R.ok().put("message","用户不存在!");
            }
        }catch (Exception e){
            String errorMessage = "更改失败!";
            log.error(errorMessage,e);
            return R.error();
        }
    }
    @PostMapping("/editUserinfo")
    public R updateUserInfo(@RequestBody UserInfoEntity userInfo)  {
        JSONObject json = new JSONObject();
        try{
            userInfoService.updateUserInfo(userInfo);
           return R.ok();
        }catch (Exception e){
            String errorMessage = "修改失败!";
            log.error(errorMessage,e);
            return R.error();
        }
    }

    @PostMapping("/onOff")
    public R switchUser(@RequestParam String userId)  {
        JSONObject json = new JSONObject();
        try{
            userInfoService.updateUserState(userId);
            return R.ok();
        }catch (Exception e){
            String errorMessage = "修改失败!";
            log.error(errorMessage,e);
            return R.error();
        }
    }
    @PostMapping("/deleteUserinfo")
    public R deleteUserInfos(@RequestBody Map<String, Object> params) {
        try{
            List<String> idList = new ArrayList<>();
            idList = (List<String>) params.get("ids");
            userInfoService.deleteUserInfos(idList);
            return R.ok();
        }catch (Exception e){
            String errorMessage = "删除失败!";
            log.error(errorMessage,e);
            return R.error();
        }
    }
    @GetMapping("/exportExcel")
    public R exportFile(String userName, String userUnit, HttpServletResponse response){
        JSONObject jsonObject = new JSONObject();
        try {
            userInfoService.exportExcel(userName,userUnit,response);
            jsonObject.put("message","导出成功");
            return R.ok();
        }catch (Exception e){
            String errorMsg = "导出失败";
            log.error("导出失败!",e);
           return R.error();
        }
    }
    @GetMapping("/deptTemplate")
    public R downloadTemplate(){
        JSONObject jsonObject = new JSONObject();
        try{
            String fileName = "UserInfo.xlsx";
            jsonObject.put("message","模板下载成功");
            return R.ok();
        }catch (Exception e){
            log.error("下载失败");
            String message = "下载失败";
            return R.error(message);
        }
    }
    @PostMapping("/uploadFile")
    public R uploadFile(MultipartFile file, HttpServletResponse response){
        try{
            String returnMsg =  userInfoService.uploadFile(file,response);
            return R.ok();
        }catch (Exception e){
            String errorMessage = "导入失败!";
            log.error(errorMessage,e);
            return R.error(errorMessage);
        }
    }
}
